package spring.chatroom.common.handler;


import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import spring.chatroom.common.utils.SessionTracker;

import java.util.Map;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

//    //他会自动的根据SessionId来获取到对饮的Session
//    @Autowired
//    HttpSession session;

    //这里校验是否登录过了
    @Override
    public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception {
        try {

            HttpSession session = request.getSession();

            //从sessionMap中找到当前的session 如果有就是登录了的
            Map<Integer, HttpSession> sessionMap = SessionTracker.getSessionMap();
            for (Integer i : sessionMap.keySet()) {
                if (session.equals(sessionMap.get(i))) {
                    return true;
                }
            }

            response.setStatus(406);
            return false;
        } catch (Exception e) {
            response.setStatus(406);
            return false;
        }

    }
}
